require('async-to-gen/register')
var fs = require('fs')
var FetchImgs = require('./fetch-imgs')
const util = require('util')

var argv = process.argv
var url = argv[2]
var selector = argv[3]
var attr = argv[4] || 'href';
var folderName = argv[5] || Math.random().toString(36).substr(2, 8)
var directory = `./imgs/${folderName}`
fs.mkdirSync(directory)

// var mix = "http://jandan.net/ooxx/page-[1,2048]#comments"
// var patt = new RegExp(/(\w+)(\d+)-(\d+)/,"g");
var patt = new RegExp(/(\w+)(:)(\/\/)([^\:|\/]+)(\:\d*)?(.*\/)([^#|\?|\n|\[]+)(\[\d+,\d+\])?(#.*)?(\?.*)?/, "g");
util.log(url)
var result = []
if ((result = patt.exec(url)) != null) {
    for (var i = 0; i < result.length; i++) {
        if (result[i] === undefined) {
            result[i] = ""
        }
        util.log("parse url:result[%d]=%s", i, result[i])
    }
}
var num = JSON.parse(result[8])
util.log("startNum:%d-endNum:%d", num[0], num[1])

for (let s = num[0]; s <= num[1]; s++) {
    var parseUrl = util.format("%s%d%s", result.slice(1, 8).join(""), s, result.slice(9, result.length).join(""))
    util.log("%s", parseUrl)
    FetchImgs.fetchImgsByReplace(parseUrl, selector, attr, directory).catch(error => console.error(error))
}




//运行方法
//node  jandan http://jandan.net/ooxx/page-[2380,2387]#comments '.text p a'